<template>
  <a-form ref="form" :model="formData" :rules="rules" layout="vertical">
    <div class="form__box">
      <a-form-item :label="`数据绑定key`" field="dataIndex">
        <template v-if="dataObj.mode === 'dataView'">
          <a-select
            v-model="formData.dataViewSel"
            allow-clear
            @change="changeDataViewSel"
          >
            <a-option value="手填">手填</a-option>
            <a-option
              v-for="option in dataObj.queryGroupList"
              :key="option.groupId + ' ' + option.queryKey"
              :value="option.groupId + ' ' + option.queryKey"
              :disabled="
                dataObj.pageData.some(
                  (item) =>
                    item.formData.dataIndex ===
                    option.groupId + ' ' + option.queryKey
                )
              "
              :title="
                (option.formName
                  ? `${option.formName}_${option.columnName}`
                  : option.columnName) +
                (option.aggregateId
                  ? `（${option.funColumnAs}的函数条件）`
                  : '')
              "
              >{{
                option.formName
                  ? `${option.formName}_${option.columnName}`
                  : option.columnName
              }}{{
                option.aggregateId ? `（${option.funColumnAs}函数条件）` : ""
              }}</a-option
            >
          </a-select>
          <a-input
            v-model="formData.dataIndex"
            :disabled="formData.dataViewSel !== '手填'"
          ></a-input>
        </template>
        <a-input
          v-else
          v-model="formData.dataIndex"
          :disabled="formData.notMod"
        ></a-input>
        <field-linkage :formData="formData"></field-linkage>
      </a-form-item>
      <a-form-item :label="`字段名称`" field="name">
        <a-input v-model="formData.name"></a-input>
        <a-checkbox v-model="formData.hideTitle">隐藏标题</a-checkbox>
      </a-form-item>
      <a-form-item label="查询数据源">
        <a-select
          v-model="formData.dataSourceId"
          @change="queryDataSourceDetails($event)"
          :filter-option="false"
          @search="queryDatasourceList"
          show-search
          allow-clear
        >
          <a-option
            v-for="item in dataSourceList"
            :key="item.dataId"
            :value="item.dataId"
            :title="item.dataName"
          >
            {{ item.dataName }}
          </a-option>
        </a-select>
        <!-- <linked-form-query :formData="formData"></linked-form-query>-->
      </a-form-item>
      <a-form-item label="展示字段">
        <a-select v-model="formData.dataShowFields" multiple allow-clear>
          <a-option
            v-for="item in dataShowFieldOptions"
            :key="item.columnAs"
            :value="item.columnAs"
          >
            {{ item.columnAs }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="展示字段排序">
        <draggable tag="div" :list="formData.dataShowFields">
          <template #item="{ element }">
            <li :key="element">
              <icon-drag-dot-vertical /> {{ element }}
            </li>
          </template>
        </draggable>
      </a-form-item>
      <a-form-item label="展示字段别名">
        <div v-for="(item, key) in formData.dataShowAlias" :key="key">
          <a-form-item :label="item.key">
            <a-input v-model="item.alias"></a-input>
          </a-form-item>
        </div>
      </a-form-item>
      <a-tabs>
        <a-tab-pane
          v-for="(groupItem, index) in formData.dataCondition"
          :title="`条件组${index + 1}`"
          :key="groupItem.tableQueryMappingAddDTO?.groupId || groupItem.groupId"
        >
          <a-form-item
            v-for="item in groupItem.tableQueryGroupAddDTOList"
            :key="item.groupId + item.columnKey"
            :label="`条件字段：${item.columnKey}`"
          >
            <template v-if="!item.between">
              <a-select
                v-model="item.dataIndex"
                allow-clear
                placeholder="请选择映射字段"
              >
                <a-option
                  v-for="option in nameList"
                  :key="option.dataIndex"
                  :value="option.dataIndex"
                  :disabled="
                    formData.dataCondition.some(
                      (e) => e.dataIndex === option.dataIndex
                    )
                  "
                  >{{ option.name }}</a-option
                >
              </a-select>
              <a-input
                v-model="item.defaultTheValue"
                placeholder="条件默认传参"
              ></a-input>
            </template>
            <template v-else>
              <span
                v-for="(betweenItem, betweenIndex) in item.between"
                :key="betweenItem.queryKey"
              >
                <a-select
                  v-model="betweenItem.dataIndex"
                  allow-clear
                  :placeholder="`请选择 条件${betweenIndex + 1} 映射字段`"
                >
                  <a-option
                    v-for="option in nameList"
                    :key="option.dataIndex"
                    :value="option.dataIndex"
                    :disabled="
                      formData.dataCondition.some(
                        (e) => e.dataIndex === option.dataIndex
                      )
                    "
                    >{{ option.name }}</a-option
                  >
                </a-select>
                <a-input
                  v-model="betweenItem.defaultTheValue"
                  :placeholder="`条件${betweenIndex + 1}默认传参`"
                ></a-input>
              </span>
            </template>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
      <a-form-item label="标题展示字段">
        <a-select v-model="formData.titleDisplay">
          <a-option
            :value="item"
            v-for="(item, index) in formData.dataShowFields"
            :key="index"
          >
            {{ item }}
          </a-option>
        </a-select>
      </a-form-item>
    </div>
  </a-form>
</template>
<script>
// import { nanoid } from 'nanoid'
// import { basicDefaultData, tagColorList, typeOptions } from '@/components/Form/base/options'
import {
  basicDefaultData,
  tagColorList,
  typeOptions,
} from "@/components/Form/base/options";
import FieldLinkage from "@/components/Form/base/fieldLinkage.vue";
import LinkedFormQuery from "@/components/Form/base/LinkedFormQuery.vue";
import _ from "lodash";
import ValidateKey from "@/components/Form/base/validateKey.vue";

export const defaultData = () => ({
  ...basicDefaultData(),
  name: " 时间轴",
  type: "timeline",
  // opts: [],
  defaultValue: "",
  dataSource: "alone",
  allowClear: false, // 支持清除
  dataSourceId: "", // 数据源ID
  dataOptionField: "", // 数据源传值字段
  dataCondition: [], // 数据源与当前表字段绑定关系
  dataShowFields: [], // 数据源展示字段
  dataShowAlias: [], // 数据源展示字段别名
  linkedFormQuery: {},
  typeFormat: "", // 日期格式
  titleDisplay: "",
});
export const dataTypeOptions = [
  // {
  //   label: 'string',
  //   value: 'string'
  // },
  // {
  //   label: 'long',
  //   value: 'long'
  // },
  // {
  //   label: 'int',
  //   value: 'int'
  // },
  // {
  //   label: 'float',
  //   value: 'float'
  // },
  // {
  //   label: 'double',
  //   value: 'double'
  // },
  {
    label: "list",
    value: "list",
  },
  // {
  //   label: 'timestamp',
  //   value: 'timestamp'
  // }
];
export default {
  name: "TimelineInfo",
  components: { ValidateKey, LinkedFormQuery, FieldLinkage },
  inject: ["dataObj"],
  data() {
    return {
      rules: {
        name: [{ required: true, message: "必填" }],
      },
      dataSourceList: [], // 数据源列表
      dataShowFieldOptions: [], // 数据源展示字段
      dataTypeOptions,
      tagColorList,
      typeOptions,
    };
  },
  computed: {
    // TimelineInfo
    formData() {
      return this.dataObj.pageData[this.dataObj.selectIndex]?.formData || {};
    },
    nameList() {
      return this.dataObj.pageData
        .filter((item) => item.formData.dataIndex && item.formData.name)
        .map((item) => {
          return {
            name: item.formData.name,
            dataIndex: item.formData.dataIndex,
          };
        });
    },
  },
  watch: {
    formData: {
      immediate: true,
      handler(newVal) {
        console.log(newVal, "newVal", newVal.dataShowFields);
        if (newVal.name === undefined) {
          this.dataObj.pageData[this.dataObj.selectIndex].formData =
            defaultData();
          console.log(
            "select",
            this.dataObj.pageData[this.dataObj.selectIndex].formData
          );
        }
      },
    },
  },
  methods: {
    // 选择了数据源，需要查询有哪些展示字段
    async queryDataSourceDetails(dataId, id, dataShowFields) {
      try {
        if (!dataId) {
          this.formData.dataCondition = [];
          return;
        }
        this.formData.dataOptionField = id || null;
        this.formData.dataShowFields = dataShowFields || [];
        const result = await this.$http.get(
          "/datasource/queryDataSourceDetail",
          {
            params: {
              dataId,
            },
          }
        );
        const { data } = result;
        const { dataColumnQueryDTOList, aggregateFunctionInfoReqDTO } = data;
        const { aggregateFunctionInfoAddDTOList } =
          aggregateFunctionInfoReqDTO || {};
        const mergedList = dataColumnQueryDTOList.concat(
          aggregateFunctionInfoAddDTOList || []
        );
        // 需要根据columnKey去重后的对象数组，而不是单纯的columnKey集合，可以进一步处理：
        this.dataShowFieldOptions = mergedList.filter((item, index, self) => {
          return index === self.findIndex((t) => t.columnAs === item.columnAs);
        });
        _.assign(this.formData, {
          dataCondition: data.queryGroupReqDTOList?.map((item) => {
            let oldData = {};
            if (id) {
              // 编辑时，先查找原先的值,旧模式
              oldData = this.formData.dataCondition?.find(
                (e) =>
                  e.groupId === item.tableQueryMappingAddDTO.groupId &&
                  e.columnKey === item.tableQueryMappingAddDTO.columnKey
              );
            }
            item.tableQueryGroupAddDTOList.forEach((queryItem) => {
              if (!_.isEmpty(oldData) && !queryItem.between) {
                queryItem.dataIndex = oldData?.dataIndex || null;
                queryItem.defaultTheValue = oldData?.defaultTheValue || null;
              } else {
                const oldV2Data = this.findMatchingQuery(
                  this.formData.dataCondition,
                  queryItem.groupId,
                  queryItem.queryKey
                );
                if (
                  _.isArray(queryItem.between) &&
                  queryItem.between.length &&
                  oldV2Data?.between
                ) {
                  queryItem.between[0] = oldV2Data?.between?.[0];
                  queryItem.between[1] = oldV2Data?.between?.[1];
                } else if (!_.isArray(queryItem.between)) {
                  queryItem.defaultTheValue =
                    oldV2Data?.defaultTheValue || null;
                  queryItem.dataIndex = oldV2Data?.dataIndex || null;
                }
              }
            });
            return _.cloneDeep(item);
          }),
        });
        console.log(this.formData.dataCondition, "输出");
      } catch (e) {
        console.error("请求失败", e);
      }
    },
    findMatchingQuery(dataCondition, groupId, queryKey) {
      for (const condition of dataCondition) {
        const group = condition.tableQueryGroupAddDTOList;
        if (group) {
          for (const item of group) {
            // 查找具有指定 groupId 和 queryKey 的对象
            if (item.groupId === groupId && item.queryKey === queryKey) {
              return item;
            }
          }
        }
      }

      return null; // 如果没有找到匹配项，则返回 null
    },
    // 查询数据源列表
    async queryDatasourceList(dataName) {
      // try {
      //   const result = await this.$http.post(`/datasource/querySourceAllList`, {
      //     dataTypeList: ["select", "selTable", "interface"],
      //     dataName: dataName || "",
      //   });
      //   const { data } = result;
      //   this.dataSourceList = data;
      // } catch (e) {
      //   console.error("请求失败", e);
      // }
    },
  },
  created() {
    this.queryDatasourceList(); // 查询数据源列表
    const { dataSourceId, dataShowFields, titleDisplay, dataShowAlias } =
      this.formData;
    if (dataSourceId) {
      this.queryDataSourceDetails(
        dataSourceId,
        true,
        dataShowFields,
        titleDisplay
      );
    }
    this.formData.dataShowAlias = (dataShowFields || []).map((item) => {
      const match = (dataShowAlias || []).find((ros) => ros.key === item);
      return {
        key: item,
        alias: match ? match.alias : undefined,
      };
    });
  },
};
</script>

<style scoped lang="less">
.opts_chunk {
  width: 100%;
  margin-top: 5px;
  margin-bottom: 5px;

  /deep/ .arco-radio-group {
    width: 100%;
  }

  .del_icon {
    // color: red;
    font-size: 16px;
    position: absolute;
    right: 10px;
    cursor: pointer;
  }

  .del_icon:hover {
    color: red;
  }
}
</style>
